const app = getApp()

Page({
  data: {
    profile: {
      bio: ''
    },
    links: []
  },

  onLoad() {
    // 加载现有数据
    this.setData({
      profile: {
        bio: app.globalData.profile?.bio || '分享我的社交账号'
      },
      links: app.globalData.links || []
    })
  },

  onBioInput(e) {
    this.setData({
      'profile.bio': e.detail.value
    })
  },

  onLinkInput(e) {
    const { index, field } = e.currentTarget.dataset
    const value = e.detail.value
    const key = `links[${index}].${field}`
    this.setData({
      [key]: value
    })
  },

  addLink() {
    const links = this.data.links
    links.push({
      name: '',
      url: '',
      icon: '/assets/icons/default.png'
    })
    this.setData({ links })
  },

  deleteLink(e) {
    const index = e.currentTarget.dataset.index
    const links = this.data.links
    links.splice(index, 1)
    this.setData({ links })
  },

  saveLinks() {
    // 验证数据
    const links = this.data.links.filter(link => link.name && link.url)
    if (links.length === 0) {
      wx.showToast({
        title: '请至少添加一个有效链接',
        icon: 'none'
      })
      return
    }

    // 保存到全局数据
    app.globalData.profile = this.data.profile
    app.globalData.links = links

    // TODO: 保存到服务器

    wx.showToast({
      title: '保存成功',
      icon: 'success',
      duration: 1500,
      success: () => {
        setTimeout(() => {
          wx.navigateBack()
        }, 1500)
      }
    })
  }
}) 